﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DataLib.Accounts.Bus;
using System.Web.Script.Serialization;

namespace Ewts.ashx
{
    /// <summary>
    /// PDInsBar 的摘要说明
    /// </summary>
    public class PDInsBar : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string strjson = "";

            if (context.Request["pdwc"] != null && context.Request["pdwc"].ToString().Trim() != "")
            {
                strjson = AddInStorage(context).id.ToString();
            }
            else if (context.Request["delbarid"] != null && context.Request["delbarid"].ToString().Trim() != "")
            {
                //删除barCode
                strjson = deleteByid(context.Request["delbarid"].ToString().Trim());
            }
            else if (context.Request["delunid"] != null && context.Request["delunid"].ToString().Trim() != "")
            {
                //删除unprocess
                new DataLib.BLL.unProcessed().Delete(int.Parse(context.Request["delunid"].ToString().Trim()));
            }
            else if (context.Request["barid"] != null && context.Request["barid"].ToString().Trim() != "")
            {
                //
                strjson = GetJsonByBarid(int.Parse(context.Request["barid"].ToString().Trim()));
            }
            else if (context.Request["isprocess"] != null && context.Request["isprocess"].ToString() != "un")
            {
                if (context.Request["storageid"] == null || context.Request["storageid"].ToString().Trim() == "0")
                {
                    strjson = "SD";
                }
            }
            else if (context.Request["delhlid"] != null && context.Request["delhlid"].ToString().Trim() != "")
            {
                new DataLib.BLL.ins_fuliao().Delete(int.Parse(context.Request["delhlid"].ToString().Trim()));
            }
            else if (context.Request["delshid"] != null && context.Request["delshid"].ToString().Trim() != "")
            {
                new DataLib.BLL.ins_sunhao().Delete(int.Parse(context.Request["delshid"].ToString().Trim()));
            }
            else
            {
                //插入记录
                DataLib.BLL.InStorage bllIn = new DataLib.BLL.InStorage();
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                DataLib.Model.InStorage inModel = new DataLib.Model.InStorage();

            

                //入库单操作，第一次就新增，否则读取传过来的入库单，绑定入库单号

               

                    inModel = AddInStorage(context);
               
                //    string instoid = context.Request["hidInStoID"].ToString().Trim();
                //    inModel = bllIn.GetModel(int.Parse(instoid));

                //}

                decimal curtotal = 0;
                decimal outtotal = 0;
                bool flag = true;


                if (context.Request["isprocess"] != null && context.Request["isprocess"].ToString().Trim() == "un")
                {
                    //分类汇总明细（处理前）
                    DataLib.Model.unProcessed unModel = new DataLib.Model.unProcessed();
                    unModel = AddUpProcess(context, (int)inModel.id);
                    strjson += serializer.Serialize(unModel);
                    strjson += ",";
                }
             
                else
                {
                    curtotal = bllIn.GetInsTotalWeight((int)inModel.id);
                    string outtype = "0";

                    if (context.Request["parid"] != null && context.Request["parid"].ToString().Trim() != "0")
                    {
                        DataLib.Model.OutStorage outmodel = new DataLib.BLL.OutStorage().GetModel(int.Parse(context.Request["parid"].ToString().Trim()));
                        outtotal = (decimal)outmodel.totalWeight;
                        outtype = outmodel.outStorageType;
                    }
                    if (context.Request["nwt"] != null)
                    {
                        flag = true;

                        //入库明细
                        DataLib.Model.BarCode barModel = new DataLib.Model.BarCode();
                        barModel = GetBarCode(context, inModel);
                        strjson += serializer.Serialize(barModel);
                        strjson += ",";

                    }
                    else
                    {
                        flag = false;
                    }
                }
                if (flag == true)
                {
                    strjson += serializer.Serialize(inModel);
                    strjson = "[" + strjson + "]";
                }
                else
                {
                    strjson = "CZ";
                }


            }

            context.Response.Write(strjson);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 添加新的入库单
        /// </summary>
        public DataLib.Model.InStorage AddInStorage(HttpContext context)
        {
            DataLib.Model.InStorage inModel = new DataLib.Model.InStorage();
            DataLib.BLL.InStorage bll = new DataLib.BLL.InStorage();

            string instoid = "0";
            if (context.Request["hidInStoID"] != null)
            {
                 instoid = context.Request["hidInStoID"].ToString().Trim();
                 if (instoid != "0")
                     inModel = bll.GetModel(int.Parse(instoid));
                 else
                     instoid = "0";
            }

            if (context.Request["oper"] != null)
            {
                inModel.Operator = context.Request["oper"].ToString().Trim();
            }
            if (context.Request["alllock"] != null && context.Request["alllock"].ToString().Trim() != "")
            {
                inModel.islock = Boolean.Parse(context.Request["alllock"].ToString());
            }
            if (context.Request["inDepart"] != null && context.Request["inDepart"].ToString().Trim() != "")
            {
                inModel.InDepart = context.Request["inDepart"].ToString().Trim();
            }
            if (context.Request["outDepart"] != null && context.Request["outDepart"].ToString().Trim() != "")
            {
                inModel.OutDepart = context.Request["outDepart"].ToString().Trim();
            }
            if (context.Request["month"] != null && context.Request["month"].ToString().Trim().Length == 6)
            {
                inModel.clearingmonth = context.Request["month"].ToString().Trim();
            }
            inModel.instoragetime = DateTime.Now;
            inModel.status = 0;

           
            inModel.cjoid = 0;
            inModel.loadnumid = 0;

            if (context.Request["parid"] != null && context.Request["parid"].ToString().Trim() != "0")
            {
                inModel.outid = int.Parse(context.Request["parid"].ToString().Trim());
                DataLib.Model.OutStorage oModel = new DataLib.BLL.OutStorage().GetModel((int)inModel.outid);
                inModel.vloadnum = oModel.VLoadNum;
            }
            else
            {
                inModel.outid = 0;
            }
            ;
            string wrlno = "";
            string intype = "";
            if (context.Request["intype"] != null && context.Request["intype"].ToString().Trim() != "")
            {
                intype = context.Request["intype"].ToString().Trim();
                wrlno = Code.NumGeneration.GetSerialNum("RP", "PinNo");
            }
            inModel.wrlno = wrlno;

            if (instoid == "0")
            {
                if (context.Request["pdwc"] != null && context.Request["pdwc"].ToString().Trim() != "")
                    inModel.mechanerr = decimal.Parse(context.Request["pdwc"].ToString().Trim());
                else
                    inModel.mechanerr = 0;
                inModel.id = bll.Add(inModel);
            }
            else
            {
                if (context.Request["pdwc"] != null && context.Request["pdwc"].ToString().Trim() != "")
                    inModel.mechanerr = decimal.Parse(context.Request["pdwc"].ToString().Trim());
                bll.Update(inModel);
            }
            return inModel;

        }


        /// <summary>
        /// 添加barcode并返回barcode的实体对象
        /// </summary>
        /// <param name="context"></param>
        /// <param name="inModel"></param>
        /// <returns></returns>
        public DataLib.Model.BarCode GetBarCode(HttpContext context, DataLib.Model.InStorage inModel)
        {


            string loadnumid = null;
            string loadnum = "";

            if (context.Request["loadnumid"] != null && context.Request["loadnumid"].ToString().Trim() != "")
            {

                loadnumid = context.Request["loadnumid"].ToString().Trim();
                if (loadnumid != "0")
                {
                    loadnum = new DataLib.BLL.LoadNum().GetModel(int.Parse(loadnumid)).loadnum;
                }
                else
                {
                    loadnum = getObjTostring(context.Request["vload"]);
                }
            }



            string strtemp = null;



            DataLib.Model.BarCode bmodel = new DataLib.Model.BarCode();
            bmodel.cjoid = int.Parse(getObjTostring(context.Request["cjoid"], "0"));
            if (loadnumid != null)
                bmodel.loadnumid = int.Parse(loadnumid);
            else
                bmodel.loadnumid = 0;
            strtemp = getObjTostring(context.Request["loadnumid"]);
            if (strtemp != null)
                bmodel.loadnumid = int.Parse(strtemp);
            else
                bmodel.loadnumid = 0;


            bmodel.comeunder = getObjTostring(context.Request["comeunder"]);


            bmodel.gwt = decimal.Parse(getObjTostring(context.Request["gwt"], "0"));

            bmodel.nwt = decimal.Parse(getObjTostring(context.Request["nwt"], "0"));

            bmodel.tare1 = decimal.Parse(getObjTostring(context.Request["tare1"], "0"));

            bmodel.tare2 = decimal.Parse(getObjTostring(context.Request["tare2"], "0"));

            bmodel.barbelong = context.Request["inDepart"].ToString();      //归属地
            bmodel.bargraphic = context.Request["outDepart"].ToString();     //处理地
            bmodel.qty = int.Parse(getObjTostring(context.Request["qty"], "0"));
            strtemp = getObjTostring(context.Request["islocak"]);
            if (strtemp != "")
                bmodel.isLocak = true;
            else
                bmodel.isLocak = false;

            bmodel.storageid = int.Parse(getObjTostring(context.Request["storageid"], "0"));
            bmodel.stroageNo = getObjTostring(context.Request["storageno"]);
            bmodel.packageno = getObjTostring(context.Request["packageno"]);
            bmodel.rdh = getObjTostring(context.Request["rdh"]);
            bmodel.remark = getObjTostring(context.Request["remark"]);
            bmodel.InStrorageID = inModel.id;
            bmodel.status = -1;
            bmodel.goodsid = getNumberByobj(context.Request["goodsid"]);
            bmodel.goodscode = getObjTostring(context.Request["goodscode"]);
            bmodel.goodsname = getObjTostring(context.Request["goodsname"]);
            bmodel.rubbishcode = getObjTostring(context.Request["rcode"]);
            bmodel.rubbishtype = getObjTostring(context.Request["rname"]);
            bmodel.plateid = getNumberByobj(context.Request["plateid"]);
            bmodel.plateno = getObjTostring(context.Request["plateno"]);
            bmodel.boxcount = getNumberByobj(context.Request["boxamount"]);


            if (context.Request["parid"] != null && context.Request["parid"].ToString().Trim() != "")
            {
                bmodel.ParmentID = int.Parse(context.Request["parid"].ToString().Trim());
            }
            else
                bmodel.ParmentID = 0;

            if (loadnumid != "0")
                bmodel.loadnumv = loadnum;
            else
            {
                if (bmodel.ParmentID != 0)
                {
                    DataLib.Model.OutStorage outModel = new DataLib.BLL.OutStorage().GetModel((int)bmodel.ParmentID);
                    bmodel.loadnumv = outModel.VLoadNum;
                }
            }

            if (context.Request["barcode"] != null && context.Request["barcode"].ToString().Trim() != "")
            {
                bmodel.barcodevalue = context.Request["barcode"].ToString().Trim();
            }
            else
            {
                bmodel.barcodevalue = Code.NumGeneration.GetSerialNum(bmodel.loadnumv + inModel.wrlno + bmodel.goodscode.PadRight(10, '0'), "BarCode");
            }


            bmodel.id = new DataLib.BLL.BarCode().Add(bmodel);
            return bmodel;

        }

        /// <summary>
        /// 当对象为空返回 "" 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string getObjTostring(object obj)
        {
            if (obj != null && obj.ToString().Trim() != "")
                return obj.ToString().Trim();
            else
                return "";
        }

        /// <summary>
        /// 当字符串为空 返回默认的值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public string getObjTostring(object obj, string def)
        {
            string str = getObjTostring(obj);
            if (str == "")
                str = def;
            return str;
        }

        /// <summary>
        /// 当对象为空，返回0
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int getNumberByobj(object obj)
        {
            if (obj != null && obj.ToString().Trim() != "")
                return int.Parse(obj.ToString());
            else
                return 0;
        }

        /// <summary>
        /// 添加未处理记录
        /// </summary>
        /// <param name="context"></param>
        public DataLib.Model.unProcessed AddUpProcess(HttpContext context, int stroageid)
        {
            DataLib.Model.unProcessed unModel = new DataLib.Model.unProcessed();
            unModel.inSid = stroageid;
            unModel.GoodsCode = getObjTostring(context.Request["goodscode_un"]);
            unModel.GoodsName = getObjTostring(context.Request["goodsname_un"]);
            string gwt = getObjTostring(context.Request["gwt_un"]);
            unModel.gwt = decimal.Parse(gwt);
            string nwt = getObjTostring(context.Request["nwt_un"]);
            unModel.nwt = decimal.Parse(nwt);
            string qty = getObjTostring(context.Request["qty_un"]);
            unModel.qty = int.Parse(qty);
            unModel.remark = getObjTostring(context.Request["remark"]);
            unModel.rubbishcode = getObjTostring(context.Request["rcode"]);
            unModel.rubbishtype = getObjTostring(context.Request["rname"]);
            unModel.status = 0;
            unModel.continNo = getObjTostring(context.Request["continno"]);
            unModel.loadnum = getObjTostring(context.Request["load"]);
            unModel.loadnumid = getNumberByobj(context.Request["loadnumid"]);
            new DataLib.BLL.unProcessed().Add(unModel);
            return unModel;
        }

        //根据id修改称重的信息
        protected string deleteByid(string id)
        {
            string result = "";
            //barcode
            DataLib.Model.BarCode barcodeModel = new DataLib.BLL.BarCode().GetModel(Convert.ToInt32(id));
            //loadnum
            DataLib.Model.LoadNum loadnumModel = new DataLib.BLL.LoadNum().GetModel(Convert.ToInt32(barcodeModel.loadnumid));
            //outstorage
            DataLib.Model.OutStorage outstorageModel = new DataLib.BLL.OutStorage().GetModel(Convert.ToInt32(barcodeModel.OutStrorageID));

            switch (barcodeModel.status)
            {
                case -1:
                    new DataLib.BLL.BarCode().Delete(Convert.ToInt32(id));
                    result = "删除成功！";
                    break;
                case 1:
                    loadnumModel.totalWeight -= barcodeModel.nwt;   //临时库入库  
                    new DataLib.BLL.LoadNum().Update(loadnumModel);         //更新loadnum表
                    barcodeModel.isdel_out = -1;                    //修改barcode的删除状态
                    new DataLib.BLL.BarCode().Update(barcodeModel);
                    result = "删除成功！";
                    break;
                case 2:
                case 4:
                case 6:             //不可删除
                case 8:
                case 10:
                    result = "已出库不可删除！";
                    break;
                case 3:
                    loadnumModel.finishWeight -= barcodeModel.nwt;  //load单已称重修改
                    new DataLib.BLL.LoadNum().Update(loadnumModel);         //更新loadnum表

                    outstorageModel.currentWeight -= barcodeModel.nwt;  //出库单修改currentweight重量
                    new DataLib.BLL.OutStorage().Update(outstorageModel);       //更新出库单数据

                    barcodeModel.isdel_out = -1;                        //修改barcode的删除状态
                    new DataLib.BLL.BarCode().Update(barcodeModel);
                    result = "删除成功！";
                    break;
                case 5:
                case 7:
                case 9:
                    outstorageModel.currentWeight -= barcodeModel.nwt;  //出库单修改currentweight重量
                    new DataLib.BLL.OutStorage().Update(outstorageModel);       //更新出库单数据
                    barcodeModel.isdel_out = -1;                        //修改barcode的删除状态
                    new DataLib.BLL.BarCode().Update(barcodeModel);
                    result = "删除成功！";
                    break;
                default:
                    result = "不合法！";
                    break;
            }

            return result;
        }

        public string GetJsonByBarid(int barid)
        {
            string strjson = "";
            DataLib.Model.BarCode bar = new DataLib.BLL.BarCode().GetModel(barid);
            if (bar != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                strjson = serializer.Serialize(bar);
            }
            return strjson;
        }

        /// <summary>
        /// 添加 ins_sunhao 记录
        /// </summary>
        /// <param name="context"></param>
        //public DataLib.Model.ins_sunhao EditSh(HttpContext context, DataLib.Model.InStorage inmodel)
        //{
        //    DataLib.Model.ins_sunhao flModel = new DataLib.Model.ins_sunhao();
        //    flModel.goodscode = getObjTostring(context.Request["gcode_sh"]);
        //    flModel.goodsname = getObjTostring(context.Request["gname_sh"]);
        //    flModel.gwt = decimal.Parse(context.Request["gwt_sh"]);
        //    flModel.nwt = decimal.Parse(getObjTostring(context.Request["nwt_sh"]));
        //    flModel.qty = int.Parse(getObjTostring(context.Request["qty_sh"]));
        //    flModel.remark = getObjTostring(context.Request["remark_sh"]);
        //    flModel.instroageid = (int)inmodel.id;
        //    flModel.wrlno = inmodel.wrlno;
        //    flModel.id = getNumberByobj(context.Request["shid"].ToString());
        //    flModel.tabno = new DataLib.BLL.ins_sunhao().GetTabNoSH();

        //    if (new DataLib.BLL.InStorage().GetConfirm((decimal)flModel.nwt, flModel.instroageid, 3) == false)
        //        return null;

        //    if (flModel.id == 0)
        //    {
        //        flModel.id = new DataLib.BLL.ins_sunhao().Add(flModel);
        //    }
        //    else
        //    {
        //        new DataLib.BLL.ins_sunhao().Update(flModel);
        //    }
        //    return flModel;
        //}

        /// <summary>
        /// 验证生产重量是否符合标准
        /// </summary>
        /// <param name="weight"></param>
        /// <param name="insid"></param>
        /// <param name="weighttype"></param>
        /// <returns></returns>
        public bool GetConfinrum(decimal weight, int insid, int weighttype)
        {
            bool flag = false;
            DataLib.BLL.InStorage insbll = new DataLib.BLL.InStorage();


            return flag;
        }

    }
}